//
//  UserAccountViewModel.swift
//  Weibo
//
//  Created by gdarkness on 16/3/20.
//  Copyright © 2016年 gdarkness. All rights reserved.
//

import UIKit

class UserAccountViewModel: NSObject {
    //MARK : --属性
    //单例
    static let shareInstance : UserAccountViewModel = UserAccountViewModel()
    private override init(){
        super.init()
        //从沙盒里面加载账号
        userAccount = loadUserAccount()
    }
    
    //账号的路径
    private let accountPath = NSSearchPathForDirectoriesInDomains(NSSearchPathDirectory.DocumentDirectory, NSSearchPathDomainMask.UserDomainMask,true).last!.stringByAppendingString("/account.plist")

    //用户账号，通过单例可以全局访问
    var userAccount : UserAccount?
    
    //是否登录。只读计算性属性
    var userLogin: Bool {
        get{
            return userAccount != nil
        }
    }
    
    //加载 access_token post
    //定义闭包, comloetion: (error:NSError?) ->()
    func loadAccessToken(code: String,completion: (error: NSError?) ->()){
        //获取accessToken的url
        let urlString = "https://api.weibo.com/oauth2/access_token"
        
        //拼接参数
        let parameters = [
            "client_id" :   client_id,
            "client_secret" : client_secret,
            "grant_type" : "authorization_code",
            "code"  :   code,
            "redirect_uri"  :   redirect_uri
        ]
        //发送请求
        //请求的url地址
        //请求参数
        NetWorkTool.shareInstance.afnManager.POST(urlString, parameters: parameters, progress: nil, success: { (_, result) -> Void in
            //将accessToken保存起来，下次直接拿出来用。省得用户每次进入都需要登录
            if let dict = result as? [String: AnyObject]{
                //将网络返回的账号赋值给属性，别人直接访问属性
                self.userAccount = UserAccount(dict: dict)
                print("userAccount: \(self.userAccount)")
                
                //保存模型到沙盒
                self.saveUserAccount()
                completion(error: nil)
            }
            
            }) { (_, error) -> Void in
                //通知控制器出现了错误
                completion(error: error)
        }
    }
    private func saveUserAccount(){
        if userAccount != nil{
            //有账号才需要保存
            print("accountPath: \(accountPath)")
            NSKeyedArchiver.archiveRootObject(userAccount!, toFile: accountPath)
        }
    }
    //发送用户信息
    func loadUserInfo(completion: (error: NSError?) -> ()) {
        //url 
        let urlString = "https://api.weibo.com/2/users/show.json"
        
        //参数
        let parameters: [String: AnyObject] = [
            "access_token": userAccount!.access_token!,
            "uid": userAccount!.uid!
        ]
        //发送请求
        NetWorkTool.shareInstance.afnManager.GET(urlString, parameters: parameters, progress: nil, success: { (_, result) -> Void in
            
            //result实际上是一个JSON -> ios里面的字典
            let dict = result as? [String: AnyObject]
            
            //给账号赋值screen_name，avatar_large
            self.userAccount?.screen_name = dict?["screen_name"] as? String
            self.userAccount?.avatar_large = dict?["avatar_large"] as? String
            
            //将账号新的数据保护到沙盒
            self.saveUserAccount()
            
            completion(error: nil)
            }) { (_, error) -> Void in
                completion(error: error)
        }
    }

    
    private func loadUserAccount() -> UserAccount? {
        let userAccount = NSKeyedUnarchiver.unarchiveObjectWithFile(accountPath) as? UserAccount
        //如果加载出账号，需要判断accessToken是否过期
        //userAccount?.expiresDate和当前时间判断
        //NSDate()
        //userAccount?.expiresDate > NSDate()表示没有过期
        //测试过期时间1。让服务器返回一个过期时间来测试 2.改模拟器时间 3.重新给userAccount?expiresDate?赋值
        //userAccount?expiresDate = NSDate(timeIntervalSinceNow: - 1000)
        if userAccount != nil && userAccount?.expiresDate?.compare(NSDate()) == NSComparisonResult.OrderedDescending{
            print("userAccount: \(userAccount)")
            return userAccount
        }
        return nil
    }
}
